import * as React from 'react';
import { injectable, postConstruct } from 'inversify';
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
import { WidgetFactory, Widget } from '@theia/core/lib/browser';
import { Tool, WEBVIEW_WIDGET_FACTORY_ID } from '../common/tools-types';
import { Message } from '@lumino/messaging';
import './style/tools.css';
@injectable()
export class WebviewWidget extends ReactWidget {

    static readonly FACTORY_ID = WEBVIEW_WIDGET_FACTORY_ID;

    private tool: Tool | null = null;
    private webviewRef = React.createRef<HTMLIFrameElement>();
    @postConstruct()
    protected init(): void {
        this.title.closable = true;
        this.title.iconClass = 'fa fa-globe';

        // ✅ 让 widget 本身可聚焦
        this.node.tabIndex = 0;
        this.node.setAttribute('role', 'widget');
        this.node.setAttribute('aria-label', 'Webview Widget');
        if(this.tool)
        {
            console.log('[Factory] Creating NEW WebviewWidget', this.tool);
            this.update()
        }
    }

    public setTool(tool: Tool): void {
        this.tool = tool;
        this.title.label = tool.name;
        this.title.caption = `${tool.name} - ${tool.url}`;
        this.title.iconClass = tool.icon || 'fa fa-globe';
    }

    protected render(): React.ReactNode {
        console.log("now render begining..........")
        if (!this.tool) {
            return (
                <div className='webview-placeholder'>
                    <div className='placeholder-content'>
                        <i className='fa fa-globe placeholder-icon'></i>
                        <p>没有可显示的工具</p>
                    </div>
                </div>
            );
        }

        return (
            <div className='webview-container'>
                <div className='webview-toolbar'>
                    <div className='webview-url'>
                        <i className={this.tool.icon || 'fa fa-globe'}></i>
                        <span>{this.tool.name}</span>
                        <small>({this.tool.url})</small>
                    </div>
                    <div className='webview-actions'>
                        <button
                            className='webview-refresh-btn'
                            onClick={this.refreshWebview.bind(this)}
                            title="刷新"
                        >
                            <i className='fa fa-refresh'></i>
                        </button>
                        <button
                            className='webview-external-btn'
                            onClick={this.openExternal.bind(this)}
                            title="在浏览器中打开"
                        >
                            <i className='fa fa-external-link'></i>
                        </button>
                    </div>
                </div>
                <iframe
                    ref={this.webviewRef}
                    src={this.tool.url}
                    className='webview-iframe'
                    title={this.tool.name}
                    sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation"
                />
            </div>
        );
    }

    private refreshWebview(): void {
       if (this.webviewRef.current && this.tool) {
            // 方法1: 重新设置 src
            const currentSrc = this.webviewRef.current.src;
            this.webviewRef.current.src = '';
            setTimeout(() => {
                if (this.webviewRef.current) {
                    this.webviewRef.current.src = currentSrc;
                }
            }, 10);
        }
    }

    private openExternal(): void {
        if (this.tool) {
            window.open(this.tool.url, '_blank');
        }
    }

   protected onActivateRequest(msg: Message): void {
        super.onActivateRequest(msg);
        setTimeout(() => {
            if (this.webviewRef.current) {
                this.webviewRef.current.focus();
            }
        }, 100);
    }
    protected onAfterAttach(msg: Message): void {
        super.onAfterAttach(msg);
        console.log('[WebviewWidget.onAfterAttach] attach 完成');
        if (this.tool) {
            this.update();
        }
    }

    protected onBeforeDetach(msg: Message): void {
        console.log('[WebviewWidget.onBeforeDetach] 即将 detach');
        super.onBeforeDetach(msg);
    }
}
